import argparse
import logging
import os
from tensorboardX import SummaryWriter
import random
import multiprocessing
import sys
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from dataset_synapse import Synapse_dataset
from dataset_kits19_512 import kits19_dataset
from utils import test_single_volume
from unet import UNet
from torchvision.utils import save_image
import cv2 as cv
import math

parser = argparse.ArgumentParser()
parser.add_argument('--volume_path', type=str,
                    default='', help='root dir for validation volume data')  # for acdc volume_path=root_dir
parser.add_argument('--dataset', type=str,
                    default='kits19', help='experiment_name')
parser.add_argument('--num_classes', type=int,
                    default=2, help='output channel of network')

parser.add_argument('--max_iterations', type=int, default=20000, help='maximum epoch number to train')
parser.add_argument('--max_epochs', type=int, default=150, help='maximum epoch number to train')
parser.add_argument('--batch_size', type=int, default=24,
                    help='batch_size per gpu')
parser.add_argument('--img_size', type=int, default=224, help='input patch size of network input')
parser.add_argument('--is_savenii', action="store_true", help='whether to save results during inference')

parser.add_argument('--n_skip', type=int, default=3, help='using number of skip-connect, default is num')
parser.add_argument('--vit_name', type=str, default='R50-ViT-B_16', help='select one vit model')

parser.add_argument('--test_save_dir', type=str, default='../predictions', help='saving prediction as nii!')
parser.add_argument('--deterministic', type=int, default=1, help='whether use deterministic training')
parser.add_argument('--base_lr', type=float, default=0.01, help='segmentation network learning rate')
parser.add_argument('--seed', type=int, default=1234, help='random seed')
parser.add_argument('--vit_patches_size', type=int, default=16, help='vit_patches_size, default is 16')
args = parser.parse_args()


def inference(args, model, log):
    db_test = args.Dataset(base_dir=args.volume_path, split="test")
    testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=multiprocessing.cpu_count())
    logging.info("{} test iterations per epoch".format(len(testloader)))
    model.eval()
    writer = SummaryWriter('/home/more/xfl/Project/Pytorch-UNet-master/kits19_test_log/')
    dice = 0.0
    hd = 0.0
    bzc_d = []
    bzc_h = []
    dice1 = 0.0
    hd1 = 0.0
    bzc1_d = []
    bzc1_h = []
    dice2 = 0.0
    hd2 = 0.0
    bzc2_d = []
    bzc2_h = []
    dice3 = 0.0
    hd3 = 0.0
    bzc3_d = []
    bzc3_h = []
    dice4 = 0.0
    hd4 = 0.0
    bzc4_d = []
    bzc4_h = []
    dice5 = 0.0
    hd5 = 0.0
    bzc5_d = []
    bzc5_h = []
    dice6 = 0.0
    hd6 = 0.0
    bzc6_d = []
    bzc6_h = []
    dice7 = 0.0
    hd7 = 0.0
    bzc7_d = []
    bzc7_h = []
    n1 = 0
    n2 = 0
    n3 = 0
    n4 = 0
    n5 = 0
    n6 = 0
    n7 = 0
    n = 0
    for i_batch, sampled_batch in tqdm(enumerate(testloader)):

        image, label = sampled_batch["image"], sampled_batch["label"]

        metric_i, pred = test_single_volume(image, label, model)

        image = image[0, 0:1, :, :]
        image = (image - image.min()) / (image.max() - image.min())
        writer.add_image('test/Image', image, i_batch)
        save_image(image, log + '/' + 'image_' + str(i_batch) + '.png')
        pred = torch.from_numpy(pred)
        pred = pred.unsqueeze(0)
        writer.add_image('test/Prediction', pred * 50, i_batch)
        pred = pred.float()

        save_image(pred, log + '/' + 'pred_' + str(i_batch) + '.png')
        labs = label * 50
        writer.add_image('test/GroundTruth', labs, i_batch)
        logging.info('idx %d  mean_dice %f mean_hd95 %f' % (i_batch, metric_i[0], metric_i[1]))
        labs = labs.float()
        save_image(labs, log + '/' + 'lab_' + str(i_batch) + '.png')

        l = label.squeeze(0)
        l = l.numpy()
        a = np.sum(l[:, :] == 1)
        b = a / (224*224)

        if b >= 0 and b < 0.1 and metric_i[0] != 0:
            dice1 += metric_i[0]
            hd1 += metric_i[1]
            n1 += 1
            bzc1_d.append(metric_i[0])
            bzc1_h.append(metric_i[1])
        if b >= 0.1 and b < 0.2 and metric_i[0] != 0:
            dice2 += metric_i[0]
            hd2 += metric_i[1]
            n2 += 1
            bzc2_d.append(metric_i[0])
            bzc2_h.append(metric_i[1])
        if b >= 0.2 and b < 0.3 and metric_i[0] != 0:
            dice3 += metric_i[0]
            hd3 += metric_i[1]
            n3 += 1
            bzc3_d.append(metric_i[0])
            bzc3_h.append(metric_i[1])
        if b >= 0.3 and b < 0.4 and metric_i[0] != 0:
            dice4 += metric_i[0]
            hd4 += metric_i[1]
            n4 += 1
            bzc4_d.append(metric_i[0])
            bzc4_h.append(metric_i[1])
        if b >= 0.4 and b < 0.5 and metric_i[0] != 0:
            dice5 += metric_i[0]
            hd5 += metric_i[1]
            n5 += 1
            bzc5_d.append(metric_i[0])
            bzc5_h.append(metric_i[1])
        if b >= 0.5 and metric_i[0] != 0:
            dice6 += metric_i[0]
            hd6 += metric_i[1]
            n6 += 1
            bzc6_d.append(metric_i[0])
            bzc6_h.append(metric_i[1])

        # if b>=0.067 and metric_i[0] != 0:
        #     dice6 += metric_i[0]
        #     hd6 += metric_i[1]
        #     n6+=1
        #     bzc6_d.append(metric_i[0])
        #     bzc6_h.append(metric_i[1])

        if metric_i[0] != 0:
            bzc_d.append(metric_i[0])
            bzc_h.append(metric_i[1])
            dice += metric_i[0]
            hd += metric_i[1]
            n = n + 1
        # bzc_d.append(metric_i[0])
        # bzc_h.append(metric_i[1])
        # dice += metric_i[0]
        # hd += metric_i[1]
        # n = n + 1

    print(n1, n2, n3, n4, n5, n6)
    dice = dice / n
    hd = hd / n

    sd = 0
    sh = 0
    for i in range(n):
        sd = (bzc_d[i] - dice) ** 2 + sd
        sh = (bzc_h[i] - hd) ** 2 + sh

    bzcd = math.sqrt(sd / n)
    bzch = math.sqrt(sh / n)

    dice1 = dice1 / n1
    hd1 = hd1 / n1

    sd = 0
    sh = 0
    for i in range(n1):
        sd = (bzc1_d[i] - dice1) ** 2 + sd
        sh = (bzc1_h[i] - hd1) ** 2 + sh

    bzcd1 = math.sqrt(sd / n1)
    bzch1 = math.sqrt(sh / n1)

    dice2 = dice2 / n2
    hd2 = hd2 / n2

    sd = 0
    sh = 0
    for i in range(n2):
        sd = (bzc2_d[i] - dice2) ** 2 + sd
        sh = (bzc2_h[i] - hd2) ** 2 + sh

    bzcd2 = math.sqrt(sd / n2)
    bzch2 = math.sqrt(sh / n2)

    dice3 = dice3 / n3
    hd3 = hd3 / n3

    sd = 0
    sh = 0
    for i in range(n3):
        sd = (bzc3_d[i] - dice3) ** 2 + sd
        sh = (bzc3_h[i] - hd3) ** 2 + sh

    bzcd3 = math.sqrt(sd / n3)
    bzch3 = math.sqrt(sh / n3)

    dice4 = dice4 / n4
    hd4 = hd4 / n4

    sd = 0
    sh = 0
    for i in range(n4):
        sd = (bzc4_d[i] - dice4) ** 2 + sd
        sh = (bzc4_h[i] - hd4) ** 2 + sh

    bzcd4 = math.sqrt(sd / n4)
    bzch4 = math.sqrt(sh / n4)

    dice5 = dice5 / n5
    hd5 = hd5 / n5

    sd = 0
    sh = 0
    for i in range(n5):
        sd = (bzc5_d[i] - dice5) ** 2 + sd
        sh = (bzc5_h[i] - hd5) ** 2 + sh

    bzcd5 = math.sqrt(sd / n5)
    bzch5 = math.sqrt(sh / n5)

    sd = 0
    sh = 0
    # dice6 = dice6 / n6
    # hd6 = hd6 / n6
    # for i in range(n6):
    #     sd = (bzc6_d[i] - dice6) ** 2 + sd
    #     sh = (bzc6_h[i] - hd6) ** 2 + sh
    #
    # bzcd6 = math.sqrt(sd / n6)
    # bzch6 = math.sqrt(sh / n6)

    # dice6 = dice6 / n6
    # hd6 = hd6 / n6
    #
    # sd = 0
    # sh = 0
    # for i in range(n6):
    #     sd = (bzc6_d[i] - dice6) ** 2 + sd
    #     sh = (bzc6_h[i] - hd6) ** 2 + sh
    #
    # bzcd6 = math.sqrt(sd / n6)
    # bzch6 = math.sqrt(sh / n6)

    logging.info(' mean_dice %f mean_hd95 %f' % (dice, hd))
    logging.info('Testing performance in best val model: mean_dice : %f mean_hd95 : %f dice1:%f hd1:%f n1: %f'
                 'dice2:%f hd2:%f n2: %f dice3:%f hd3:%f n3: %f dice4:%f hd4:%f n4: %f dice5:%f hd5:%f n5: %f'
                 % (dice, hd, dice1, hd1, n1, dice2, hd2, n2,
                    dice3, hd3, n3, dice4, hd4, n4, dice5, hd5, n5))
    logging.info(
        ' bzc: bzc1: %f, %f, bzc2: %f, %f, bzc3: %f, %f, bzc4: %f, %f, bzc5: %f, %f'
        'bzc: %f, %f' % (
        bzcd1, bzch1, bzcd2, bzch2, bzcd3, bzch3, bzcd4, bzch4, bzcd5, bzch5, bzcd, bzch))

    return "Testing Finished!"


if __name__ == "__main__":

    if not args.deterministic:
        cudnn.benchmark = True
        cudnn.deterministic = False
    else:
        cudnn.benchmark = False
        cudnn.deterministic = True
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    dataset_config = {
        'kits19': {
            'Dataset': kits19_dataset,
            'volume_path': '/home/more/xfl/Data/kits19/',
            'num_classes': 2,
        },
        'Renal': {
            'Dataset': Synapse_dataset,
            'volume_path': '/home/more/xfl/Data/Renal/',
            'num_classes': 2,
        }
    }
    dataset_name = 'kits19'
    args.num_classes = dataset_config[dataset_name]['num_classes']
    args.volume_path = dataset_config[dataset_name]['volume_path']
    args.Dataset = dataset_config[dataset_name]['Dataset']

    args.is_pretrain = True

    # name the same snapshot defined in train script!

    args.exp = 'yU_' + dataset_name + str(args.img_size)
    snapshot_path = "./model/{}/{}".format(args.exp, 'U')
    snapshot_path = snapshot_path + '_pretrain' if args.is_pretrain else snapshot_path
    snapshot_path = snapshot_path + '_' + str(args.max_iterations)[
                                          0:2] + 'k' if args.max_iterations != 30000 else snapshot_path
    snapshot_path = snapshot_path + '_epo' + str(args.max_epochs) if args.max_epochs != 30 else snapshot_path
    snapshot_path = snapshot_path + '_bs' + str(args.batch_size)
    snapshot_path = snapshot_path + '_lr' + str(args.base_lr) if args.base_lr != 0.01 else snapshot_path
    snapshot_path = snapshot_path + '_' + str(args.img_size)
    snapshot_path = snapshot_path + '_s' + str(args.seed) if args.seed != 1234 else snapshot_path

    net = UNet(n_channels=3, n_classes=2).cuda()

    snapshot = os.path.join(snapshot_path, 'best_model.pth')
    if not os.path.exists(snapshot): snapshot = snapshot.replace('best_model', 'epoch_' + str(150 - 1))
    net.load_state_dict(torch.load(
        '/home/more/xfl/Project/Pytorch-UNet-master/model/U_kits19224/U_pretrain_epo150_bs24_224/epoch_149.pth'))
    snapshot_name = snapshot_path.split('/')[-1]

    log_folder = './renal_test_log/test_log_' + args.exp + 'yuzhi'
    os.makedirs(log_folder, exist_ok=True)
    logging.basicConfig(filename=log_folder + '/' + snapshot_name + ".txt", level=logging.INFO,
                        format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
    logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
    logging.info(str(args))
    logging.info(snapshot_name)

    inference(args, net, log_folder)
